'use strict';

const bcrypt = require('bcryptjs');

async function createDemoUser() {
  try {
    console.log('开始创建演示用户...');
    
    // 使用Sequelize连接数据库
    const { Sequelize } = require('sequelize');
    
    const dbConfig = {
      host: process.env.MySqlHost || '127.0.0.1',
      port: process.env.MySqlPort || 3306,
      user: process.env.MySqlUsername || 'root',
      password: process.env.MySqlPassword || '302108jw302',
    };
    
    const dbName = process.env.MySqlDatabase || 'wardrobe_db';
    
    const sequelize = new Sequelize(dbName, dbConfig.user, dbConfig.password, {
      host: dbConfig.host,
      port: dbConfig.port,
      dialect: 'mysql',
      logging: false, // 关闭SQL日志
      define: {
        raw: true,
        underscored: true,
        charset: 'utf8mb4',
        timestamps: true,
        paranoid: true,
        freezeTableName: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
      },
      dialectOptions: {
        dateStrings: true,
        typeCast: true,
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci',
      },
      timezone: '+08:00',
    });
    
    // 测试连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查用户是否已存在
    const [existingUsers] = await sequelize.query(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      { replacements: ['demo', 'demo@example.com'] }
    );
    
    if (existingUsers.length > 0) {
      console.log('演示用户已存在，跳过创建');
      await sequelize.close();
      return;
    }
    
    // 创建演示用户
    const hashedPassword = await bcrypt.hash('123456', 10);
    
    await sequelize.query(
      `INSERT INTO users (username, email, password, nickname, gender, status, created_at, updated_at) 
       VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())`,
      {
        replacements: [
          'demo',
          'demo@example.com',
          hashedPassword,
          '演示用户',
          'other',
          'active'
        ]
      }
    );
    
    console.log('演示用户创建成功！');
    console.log('用户名: demo');
    console.log('密码: 123456');
    console.log('邮箱: demo@example.com');
    
    await sequelize.close();
    
  } catch (error) {
    console.error('创建演示用户失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此文件
if (require.main === module) {
  createDemoUser();
}

module.exports = createDemoUser;
